package com.dwxt.cms.controller;


import com.dwxt.cms.entity.Role;
import com.dwxt.cms.entity.UserRole;
import com.dwxt.cms.entity.dto.RoleDTO;
import com.dwxt.cms.entity.vo.RoleVO;
import com.dwxt.cms.service.RoleServiceAdmin;
import com.dwxt.cms.service.UserRoleServiceAdmin;
import com.dwxt.common.annotation.ValidateFiled;
import com.dwxt.common.annotation.ValidateGroup;
import com.dwxt.common.base.BaseResult;
import com.dwxt.common.base.StatusCode;
import com.dwxt.common.util.PartyUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/admin/role")
public class RoleControllerAdmin {

    @Autowired
    private RoleServiceAdmin roleServiceAdmin;

    @Autowired
    private UserRoleServiceAdmin userRoleServiceAdmin;

    /**
     * @param roleDTO(顶级菜单Id,权限种类)
     * @return
     */
    @PostMapping("/createOrUpdateRole")
    @ValidateGroup(fileds = {
            @ValidateFiled(index = 0, filedName = "name", notNull = true),
            @ValidateFiled(index = 0, filedName = "categoryList", notNull = true),
            @ValidateFiled(index = 0, filedName = "menuIds", notNull = true),
    })
    public BaseResult createOrUpdateRole(RoleDTO roleDTO) {
        return roleServiceAdmin.createOrUpdateRole(roleDTO);
    }

    @DeleteMapping("/delete")
    public BaseResult delete(Integer id) {
        List<UserRole> userRoles = userRoleServiceAdmin.selectByRoleId(id);
        if (!userRoles.isEmpty()) {
            return BaseResult.build(StatusCode.ROLE_IS_USED);
        } else {
            int i = roleServiceAdmin.deleteByPrimaryKey(id);
            return i == 0 ? BaseResult.build(StatusCode.ROLE_NOT_EXIST) : BaseResult.ok();
        }
    }


    @GetMapping("/pageList")
    @ValidateGroup(fileds = {
            @ValidateFiled(index = 0, notNull = true),
            @ValidateFiled(index = 1, notNull = true),
    })
    public BaseResult pageList(Integer pageSize, Integer pageNum) {
        PageHelper.startPage(pageNum, pageSize);
        return roleServiceAdmin.selectAllRoleVo();
    }

    /**
     * 获取所有角色
     *
     * @return
     */
    @GetMapping("/all")
    public BaseResult all() {
        List<Role> roles = roleServiceAdmin.selectAllRole();
        return BaseResult.ok(roles);
    }


}
